let username = localStorage.getItem('username')
let token = localStorage.getItem('token')
let id = localStorage.getItem('id')
if (username && token) {
  $('.login-reg p').eq(0).css('display', 'none')
  $('.login-reg p').eq(1).css('display', 'block')
  $('.loginInfo').html(username)
} else {
  $('.login-reg p').eq(0).css('display', 'block')
  $('.login-reg p').eq(1).css('display', 'none')
  $('.loginInfo').html()
}
$.get('./data/navData.json', function (res) {
  let data = res.data.myJd
  let str = ''
  data.data.forEach((item) => {
    str += `<a href="javascript:;"><span>${item}</span></a>`
  })
  $('.mu_jd_menu1').html(str)
  let str2 = ''
  data.data2.forEach((item) => {
    str2 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  $('.mu_jd_menu2').html(str2)
  let data2 = res.data.qiye
  let str3 = ''
  data2.data.forEach((item) => {
    str3 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  $('.qiye_menu1').html(str3)

  let data3 = res.data.kehu.kehu
  let str4 = ''
  data3.data.forEach((item) => {
    str4 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  str4 = `<div class="kehu_menu1_top">${data3.top}</div>${str4}`
  $('.kehu_menu1').html(str4)

  let data4 = res.data.kehu.shanghu
  let str5 = ''
  data4.data.forEach((item) => {
    str5 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  str5 = `<div class="kehu_menu2_top">${data4.top}</div>${str5}`
  $('.kehu_menu2').html(str5)

  let data5 = res.data.wangzhan.tese
  let str6 = ''
  data5.data.forEach((item) => {
    str6 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  str6 = `<div class="wangzhan_menu1_top">${data5.top}</div>${str6}`
  $('.wangzhan_menu1').html(str6)

  let data6 = res.data.wangzhan.hangye
  let str7 = ''
  data6.data.forEach((item) => {
    str7 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  str7 = `<div class="wangzhan_menu2_top">${data6.top}</div>${str7}`
  $('.wangzhan_menu2').html(str7)

  let data7 = res.data.wangzhan.shanghuo
  let str8 = ''
  data7.data.forEach((item) => {
    str8 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  str8 = `<div class="wangzhan_menu3_top">${data7.top}</div>${str8}`
  $('.wangzhan_menu3').html(str8)

  let data8 = res.data.wangzhan.dengduo
  let str9 = ''
  data8.data.forEach((item) => {
    str9 += `<a href="javascript:;"><span>${item}</span></a>`
  })
  str9 = `<div class="wangzhan_menu4_top">${data8.top}</div>${str9}`
  $('.wangzhan_menu4').html(str9)
})

let goodsList = document.querySelector('.goodsList')
showShopCart()
function showShopCart() {
  if (id) {
    axios.get(selectCartUrl, { params: { id } }).then(function (res) {
      let carArr = res.data.data
      if (carArr.length == 0) {
        $('.kong').css('display', 'block')
        $('.shopBox').css('display', 'none')
        zongshu()
      } else {
        $('.kong').css('display', 'none')
        $('.shopBox').css('display', 'block')
        let strArr = Array.from(carArr).map(function (item) {
          return ` <div class="goodsItem ">
          <div class="goodsInfoBox clear">
            <div class="checkTot">
              <input type="checkbox" class="checkTotle" data-pid=${item.pid}>
            </div>
            <div class="goodsInfo">
              <div class="goodsImg">
                <a href="detail.html?"+${item.pid}>
                  <img src=${item.pimg} alt=${item.pname}>
                </a>
              </div>
              <div class="goodsMsg">
                <div class="name">
                  <a href="detail.html?"+${item.pid}>
                    ${item.pdesc}
                  </a>
                </div>
                <div class="fuwu">
                  <p>
                    <i></i><span>选服务</span>
                  </p>
                </div>
              </div>
              
            </div>
            <div class="goodsProps">
              <div>
                <span>${item.pname}</span>
              </div>
            </div>
            <div class="totlePrice">
              <span>￥<i class="pprice">${item.pprice}</i></span>
            </div>
            <div class="quantity">
              <div>
                <button class="reduce" data-pid=${
                  item.pid
                }>-</button><input type="text" data-pid=${item.pid} min="1" max="99" class="num" value=${item.pnum}><button class="add" data-pid=${item.pid}>+</button>
              </div>
            </div>
            <div class="pprice-sum">
              <span>￥<i class="priceSum">${item.pnum * item.pprice}</i></span>
            </div>
            <div class="operate">
              <a data-pid=${
                item.pid
              } href="javascript:;" class="removeCart">删除</a>
            </div>
          </div>
        </div>`
        })
        let str = strArr.join('')
        goodsList.innerHTML = str
        removeCart()
        CheckCart()
        addSubBtnEvent()
        numAll()
        zongshu()
      }
    })
  } else {
    $('.kong').css('display', 'block')
    $('.shopBox').css('display', 'none')
  }
}
//给按钮添加删除事件
function removeCart() {
  let removeCart = document.querySelectorAll('.removeCart')
  Array.from(removeCart).forEach(function (item) {
    item.onclick = removeCartEvent
  })
}
//删除事件
function removeCartEvent() {
  if (confirm('确定删除删除该商品吗')) {
    let uid = id
    let pid = this.getAttribute('data-pid')
    axios.get(removeCartUrl, { params: { pid, uid } }).then(function (res) {
      alert(res.data.msg)
      showShopCart()
    })
  } else {
    return false
  }
}

//添加全选反选
function CheckCart() {
  let singleCheck = document.querySelectorAll('.checkTotle')
  let checkAll = document.querySelector('.checkAll')
  let fotCheckAll = document.querySelector('.jiesuanAllBtn')
  let Allprice = document.querySelector('.allPrice')
  Array.from(singleCheck).forEach(function (item) {
    item.onchange = function () {
      let flag = Array.from(singleCheck).every(function (item) {
        return item.checked == true
      })
      if (flag) {
        checkAll.checked = true
        fotCheckAll.checked = true
        numAll()
      } else {
        checkAll.checked = false
        fotCheckAll.checked = false
        numAll()
      }
    }
  })
  checkAll.onchange = function () {
    if (checkAll.checked) {
      Array.from(singleCheck).forEach(function (item) {
        item.checked = true
        fotCheckAll.checked = true
        numAll()
      })
    } else {
      Array.from(singleCheck).forEach(function (item) {
        item.checked = false
        fotCheckAll.checked = false
        Allprice.innerHTML = 0
      })
    }
  }
  fotCheckAll.onchange = function () {
    if (fotCheckAll.checked) {
      Array.from(singleCheck).forEach(function (item) {
        item.checked = true
        checkAll.checked = true
        numAll()
      })
    } else {
      Array.from(singleCheck).forEach(function (item) {
        item.checked = false
        checkAll.checked = false
        Allprice.innerHTML = 0
      })
    }
  }
}

//总价
function numAll() {
  let singleCheck = document.querySelectorAll('.checkTotle')
  let Allprice = document.querySelector('.allPrice')
  let sNum = document.querySelector('.snum')
  let num = 0
  let sum = 0
  Array.from(singleCheck).forEach(function (item) {
    if (item.checked) {
      let pnum = item.parentNode.parentNode.querySelector('.num')
      let pprice = item.parentNode.parentNode.querySelector('.pprice')
      let price = pnum.value * pprice.innerHTML
      num += price
      sum += Number(pnum.value)
    }
  })
  Allprice.innerHTML = num
  sNum.innerHTML = sum
}
//购物车数字
zongshu()
function zongshu() {
  let shopNum = document.querySelector('.search-shop-num')
  if (id) {
    axios.get(selectCartUrl, { params: { id } }).then(function (res) {
      let arr = res.data.data
      let snum = 0
      Array.from(arr).map(function (item) {
        return (snum += Number(item.pnum))
      })
      shopNum.innerHTML = snum
    })
  } else {
    shopNum.innerHTML = 0
  }
}

//加减商品
function addSubBtnEvent() {
  let addNum = document.querySelectorAll('.add')
  let subNum = document.querySelectorAll('.reduce')
  let showNum = document.querySelectorAll('.num')

  Array.from(subNum).forEach(function (item, i) {
    item.onclick = async function () {
      let pnum = parseInt(showNum[i].value)
      let pid = this.getAttribute('data-pid')
      let pprice =
        item.parentNode.parentNode.parentNode.querySelector('.pprice').innerHTML
      let totlePrice =
        item.parentNode.parentNode.parentNode.querySelector('.priceSum')
      if (pnum <= 1) {
        pnum = 1
        // let flag = window.confirm('确定要删除该商品吗')
        // if (flag) {
        //   let uid = id
        //   axios.get(removeCartUrl, { params: { pid, uid } }).then(function (res) {
        //     alert(res.data.msg)
        //     totlePrice.innerHTML = pnum * pprice
        //     numAll()
        //     showShopCart()
        //   })
        // } else {
        //   await upShopCart(pid, 1)
        //   pnum = 1
        //   showNum[i].value = pnum
        //   totlePrice.innerHTML = pnum * pprice
        //   numAll()
        // }
      } else {
        pnum--
        upShopCart(pid, -1)
        showNum[i].value = pnum
        totlePrice.innerHTML = pnum * pprice
        numAll()
      }

      return false
    }
  })
  Array.from(addNum).forEach(function (item, i) {
    let pnum = parseInt(showNum[i].value)
    item.onclick = function () {
      let pid = this.getAttribute('data-pid')
      pnum++
      upShopCart(pid, 1)
      showNum[i].value = pnum
      let pprice =
        item.parentNode.parentNode.parentNode.querySelector('.pprice').innerHTML
      let totlePrice =
        item.parentNode.parentNode.parentNode.querySelector('.priceSum')
      totlePrice.innerHTML = pprice * pnum
      numAll()
      return false
    }
  })

  Array.from(showNum).forEach(function (item, i) {
    item.onfocus = function () {
      let numstart = this.value
      this.onchange = () => {
        let pid = this.getAttribute('data-pid')
        let numend = Number(this.value)
        if (numend <= 1) {
          numend = 1
          this.value = 1
          // let flag = window.confirm('确定要删除该商品吗')
          // if (flag) {
          //   let uid = id
          //   axios.get(removeCartUrl, { params: { pid, uid } }).then(function (res) {
          //     alert(res.data.msg)
          //     numAll()
          //     showShopCart()
          //   })
          // } else {
          //   numAll()
          //   showShopCart()
          //   this.value = numstart
          // }
          // return false
        } else if (numend >= 99) {
          this.value = 99
          numend = 99
        } else if (numend < 0) {
          this.value = 1
          numend = 1
        }
        let num = numend - numstart
        if (num == 0) {
          return false
        }
        let pprice =
          this.parentNode.parentNode.parentNode.querySelector(
            '.pprice'
          ).innerHTML
        let totlePrice =
          this.parentNode.parentNode.parentNode.querySelector('.priceSum')
        totlePrice.innerHTML = pprice * numend
        upShopCart(pid, num)
        numAll()
      }
    }
  })
}

//修改购物车
function upShopCart(pid, pnum) {
  let uid = id
  axios.get(addCartUrl, { params: { pid, uid, pnum } }).then(function (res) {})
}

//删除选中
let removeCheck = document.querySelector('.removeChecked')
removeCheck.onclick = removeChecked
function removeChecked() {
  let uid = id
  let singleCheck = document.querySelectorAll('.checkTotle')
  Array.from(singleCheck).forEach(async function (item) {
    if (item.checked) {
      let pid = item.getAttribute('data-pid')
      await axios
        .get(removeCartUrl, { params: { pid, uid } })
        .then(function (res) {})
      showShopCart()
      numAll()
    }
  })
}
let clearAll = document.querySelector('.clearAll')
clearAll.onclick = removeAll
//删除全部
function removeAll() {
  let uid = id
  axios.get(selectCartUrl, { params: { id } }).then(function (res) {
    let arr = res.data.data
    let idArr = []
    Array.from(arr).forEach(function (item) {
      idArr.push(item.pid)
    })
    idArr.forEach(function (v) {
      let pid = v
      axios.get(removeCartUrl, { params: { pid, uid } }).then(function (res) {
        showShopCart()
      })
    })
  })
}
lazyload()
function lazyload() {
  let pagesize = 20
  let pagenum = 0
  axios
    .get(productShowUrl, { params: { pagesize, pagenum } })
    .then(function (res) {
      if ((res.status = 200)) {
        let str = ''
        let proArr = res.data.data
        for (let i = 0; i < proArr.length; i++) {
          str += `<li>
        <a href="detail.html?id=${proArr[i].pid}">
          <div>
            <img src=${proArr[i].pimg} alt="">
          </div>
          <div>
            <p><i>自营</i><span>${proArr[i].pdesc}</span></p>
            <div>
              <div>
                <i>￥</i><span>${proArr[i].pprice}</span><span>.00</span>
              </div>
              <p>
                <i>券</i>
              </p>
            </div>
          </div>
        </a>
      </li>`
        }
        let str2 = $('.main-con-con').html()
        $('.main-con-con').html(str2 + str)
      }
    })
}

//搜索
select.oninput = function () {
  let list = document.querySelector('.searchlist')
  list.style.display = 'block'
  if (select.value.length != 0) {
    let value = select.value
    var url = `https://www.baidu.com/sugrec?callback=list&prod=pc_hao123&wd=${value}`
    var script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)
  } else {
    list.innerHTML = ''
  }
}
function liClick() {
  let listItem = document.querySelector('.searchlist').children
  Array.from(listItem).forEach(function (item) {
    item.onclick = function () {
      select.value = this.innerHTML
      let list = document.querySelector('.searchlist')
      list.style.display = 'none'
    }
  })
}
function list(res) {
  let arr = res.g
  let list = document.querySelector('.searchlist')
  let str = ''
  if (arr != undefined) {
    let brr = arr.map(function (item) {
      return `<li>${item.q}</li>`
    })
    str = brr.join('')
    list.innerHTML = str
    liClick()
  } else {
    list.innerHTML = ''
  }
}
//退出
$('.tuichu').click(function () {
  localStorage.removeItem('username')
  localStorage.removeItem('id')
  localStorage.removeItem('token')
  location.href = 'index.html'
})
